package com.blb.bookms.controller;

import com.blb.bookms.entity.Book;
import com.blb.bookms.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class BookController {

    @Autowired
    private BookService bookService;

    @RequestMapping("toAdd")
    public String toAdd(){
        return "add";
    }

    /**
     * 查所有书
     * @param model
     * @return
     */
    @RequestMapping("/book-list")
    public String findAll(Model model){
        List<Book> all = bookService.findAll();
        model.addAttribute("books", all);
        return "list";
    }

    @RequestMapping("/add-book")
    public String addBook(Book book){
        bookService.save(book);
        return "redirect:/book-list";
    }

    @RequestMapping("/find-book")
    public String findById(Long id,Model model){
        Book book = bookService.findById(id);
        model.addAttribute("book",book);
        return "update";
    }

    @RequestMapping("/update-book")
    public String updateBook(Book book){
        bookService.update(book);
        return "redirect:/book-list";
    }

    @RequestMapping("/delete-book")
    public String deleteBook(Long id){
        bookService.removeById(id);
        return "redirect:/book-list";
    }
}
